package com.my.utils;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class JsonUtils {

    /**
     * use gson format object to json
     *
     * @param object
     * @return json
     */
    public static String toJson(Object object) {
        Gson gson = new Gson();
        try {
            return gson.toJson(object);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * use gson format object to json
     * and Without Expose
     *
     * @param object
     * @return json string
     */
    public static String toJsonWithoutExpose(Object object) {

        GsonBuilder gb = new GsonBuilder();
        gb.excludeFieldsWithoutExposeAnnotation();
        Gson gson = gb.create();
        try {
            return gson.toJson(object);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static <T> T fromJson(String json, Class<T> classOfT) {
        Gson gson = new Gson();
        try {
            return gson.fromJson(json, classOfT);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static <T> List<T> fromJsonToList(String json, Class<T> classOfT) {

        return null;
    }

    public static <T> List<T> fromJsonToListByKey(String json, String key, Class<T> classOfT) {
        List<T> records = new ArrayList<T>();
        try {
            JSONObject object = new JSONObject(json);
            JSONArray array = object.getJSONArray(key);
            for (Object obj : array) {
                T record = fromJson(obj.toString(), classOfT);
                records.add(record);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return records;
    }


}
